<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\CommonEnum;
use app\enum\TokenEnum;
use app\model\ClientAccountModel;
use app\model\MediaAccountModel;
use app\model\MediaTokenModel;
use app\service\kuaishou\TokenService as KsTokenService;
use app\service\kuaishouesp\TokenService as KsEspTokenService;
use app\service\ocean\TokenService as OeTokenService;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Cache;

class RefreshAccountTokenWork extends BaseWork
{
    protected object $service;

    protected string $limitRedisKey;

    protected function configure()
    {
        // 指令配置
        $this->setName('refresh_account_token_work');
        $this->setDescription('刷新账户token');
        $this->addArgument('media_id', Argument::REQUIRED, '媒体id');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $mediaId = intval($input->getArgument('media_id'));
        $this->setService($mediaId);
        $limitNum = intval($this->getRedisLimit($mediaId));
        $output->writeln('=======刷新账户token开始' . date('Y-m-d H:i:s', time()) . '=======');
        $appTokens = $this->_getMediaAppToken($mediaId);

        $accounts = $this->_getLimitAccount($mediaId, $limitNum);
        if (! empty($appTokens) && ! empty($accounts)) {
            try {
                foreach ($accounts as $v) {
                    foreach ($appTokens as $val) {
                        // 判断是否已存在，已存在不执行
                        $isExist = $this->_getAccountToken($val->id, $v->id);
                        if (! $isExist) {
                            $res = $this->service::refreshAdv($val, $v);
                            if (! $res) {
                                $output->writeln('=======刷新账户token失败:' . $val->id . '-' . $v->advertiser_id . $this->service::getError(0) . date('Y-m-d H:i:s', time()) . '=======');
                            }
                        }
                    }
                    $this->setRedisLimit($v->id);
                }
            } catch (\Exception $e) {
                dump($e);
                $output->writeln('=======刷新账户token失败' . $e->getMessage() . date('Y-m-d H:i:s', time()) . '=======');
            }
        }


        $output->writeln('=======刷新账户token结束' . date('Y-m-d H:i:s', time()) . '=======');
        $output->writeln('success');
    }

    /**
     * 获取账户.
     */
    private function _getLimitAccount(int $mediaId, int $num)
    {
        return ClientAccountModel::where('id', '>', $num)->where('media_id', $mediaId)->select();
    }

    /**
     * 获取媒体app-token.
     */
    private function _getMediaAppToken(int $mediaId)
    {
        return MediaTokenModel::where('media_id', $mediaId)->select();
    }

    /**
     * 获取账户token是否存在.
     */
    private function _getAccountToken(int $tokenId, int $accountId)
    {
        return MediaAccountModel::where('media_token_id', $tokenId)->where('account_id', $accountId)->find();
    }

    private function setService(int $mediaId)
    {
        if ($mediaId == CommonEnum::OE_MEDIA) {
            $this->service = new OeTokenService();
        } elseif ($mediaId == CommonEnum::KS_MEDIA) {
            $this->service = new KsTokenService();
        } elseif ($mediaId == CommonEnum::KS_ESP_MEDIA) {
            $this->service = new KsEspTokenService();
        }
    }

    /**
     * 获取redis媒体对应的起始num.
     * @return mixed
     */
    private function getRedisLimit(int $mediaId)
    {
        $redis = Cache::store('redis')->handler();
        $limitRedisKey = '';
        if ($mediaId == CommonEnum::OE_MEDIA) {
            $limitRedisKey = TokenEnum::OE_LIMIT_REDIS_KEY;
        } elseif ($mediaId == CommonEnum::KS_MEDIA) {
            $limitRedisKey = TokenEnum::KS_LIMIT_REDIS_KEY;
        } elseif ($mediaId == CommonEnum::KS_ESP_MEDIA) {
            $limitRedisKey = TokenEnum::KS_ESP_LIMIT_REDIS_KEY;
        }
        $this->limitRedisKey = $limitRedisKey;
        return $redis->get($limitRedisKey) ?: 0;
    }

    /**
     * 刷新redis起始数.
     * @return mixed
     */
    private function setRedisLimit(int $limit)
    {
        $redis = Cache::store('redis')->handler();
        return $redis->set($this->limitRedisKey, $limit);
    }
}
